package com.kaibes.im.view.fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.kaibes.im.R;
import com.kaibes.im.control.activity.PhotoMenuActivity;
import com.kaibes.im.model.SocketWorker;
import com.kaibes.im.model.hanlder.BaseHandler;
import com.kaibes.im.utils.BirthUtil;
import com.kaibes.im.utils.StaticValuesUtil;

public class UserInformationFragment extends KaibesFragment implements
	OnClickListener {

    public static final int REFRESH_PHOTO = 0X1;
    public static final int REFRESH_TEXT = 0X2;

    public static final int REQUEST_CODE_PHOTOMENU = 0x1;
    public static final int REQUEST_CODE_GET_CONTENT = 0x2;
    public static final int REQUEST_CODE_CROP = 0x4;

    private String tempPhotoPath = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
	setHandler(new BaseHandler<UserInformationFragment>(this) {

	    @Override
	    public void handleMessage(Message msg) {
		switch (msg.what) {
		case REFRESH_PHOTO:
		    initPhoto();
		    break;

		case REFRESH_TEXT:
		    initText();
		    break;

		default:
		    break;
		}
	    }
	});
	tempPhotoPath = getKaibesApplication().getUserCacheFolder()
		+ File.separator + StaticValuesUtil.TMP_PHOTO;

	super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
	View rootView = inflater.inflate(R.layout.fragment_userinformation_1,
		container, false);

	rootView.findViewById(R.id.ivUserinformationPhoto).setOnClickListener(
		this);
	rootView.findViewById(R.id.tvUserinformationEdit).setOnClickListener(
		this);
	rootView.findViewById(R.id.tvUserinformationBack).setOnClickListener(
		this);

	return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
	initPhoto();
	initText();
	super.onActivityCreated(savedInstanceState);
    }

    private void initPhoto() {
	if (getKaibesApplication().getUserPhotoBitmap() != null) {
	    ((ImageView) getView().findViewById(R.id.ivUserinformationPhoto))
		    .setImageBitmap(getKaibesApplication().getUserPhotoBitmap());
	}
    }

    private void initText() {
	((TextView) getView().findViewById(R.id.tvUserinformationRemarks))
		.setText(getKaibesApplication().getUserInformationData()
			.getNickname());
	((TextView) getView().findViewById(R.id.tvUserinformationNickname))
		.setText(getKaibesApplication().getUserInformationData()
			.getNickname());
	((TextView) getView().findViewById(R.id.tvUserinformationUsername))
		.setText(getKaibesApplication().getUserInformationData()
			.getUsername());
	((TextView) getView().findViewById(R.id.tvUserinformationInformation))
		.setText(getKaibesApplication().getUserInformationData()
			.getSex()
			+ " "
			+ BirthUtil.getAge(getKaibesApplication()
				.getUserInformationData().getBirth())
			+ " "
			+ getKaibesApplication().getUserInformationData()
				.getAddress());
	((TextView) getView().findViewById(R.id.tvUserinformationSignature))
		.setText(getKaibesApplication().getUserInformationData()
			.getSignature());
    }

    @Override
    protected void reset() {
	if (getKaibesApplication().getUserPhotoBitmap() != null) {
	    initPhoto();
	}
	initText();
    }

    @Override
    public boolean onBackPressed() {
	getKaibesActivity().changeFragment(getLastFragmentAndSetNull());
	return false;
    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {

	case R.id.ivUserinformationPhoto: {
	    Intent intent = new Intent(getKaibesActivity(),
		    PhotoMenuActivity.class);
	    startActivityForResult(intent, REQUEST_CODE_PHOTOMENU);
	    break;
	}

	case R.id.tvUserinformationEdit:
	    getKaibesActivity().changeFragment(
		    UserInformationEditFragment.class);
	    break;

	case R.id.tvUserinformationBack:
	    getKaibesActivity().changeFragment(getLastFragmentAndSetNull());
	    break;

	default:
	    break;
	}
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
	if (hidden == false) {
	    refresh(1);
	}
	super.onHiddenChanged(hidden);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == REQUEST_CODE_PHOTOMENU) {
	    switch (resultCode) {
	    case PhotoMenuActivity.RESULT_CODE_CANCEL:
		break;
	    case PhotoMenuActivity.RESULT_CODE_CHANGE:
		chooseImage();
		break;
	    case PhotoMenuActivity.RESULT_CODE_SET:
		// TODO 设置挂饰
		break;
	    case PhotoMenuActivity.RESULT_CODE_SHOW:
		getKaibesApplication().setPhotoshowBitmap(
			getKaibesApplication().getUserPhotoBitmap());
		getKaibesActivity().changeFragment(PhotoShowFragment.class);
		break;

	    default:
		break;
	    }
	}

	if (requestCode == REQUEST_CODE_GET_CONTENT) {
	    if (resultCode == Activity.RESULT_OK) {
		if (data.getData() != null) {
		    String path = data
			    .getData()
			    .toString()
			    .substring("content://".length(),
				    data.getData().toString().length());
		    if (path.startsWith("com.")) {
			cropImage(300, 300, Uri.fromFile(new File(getPath(
				getActivity(), data.getData()))));
		    } else {
			cropImage(300, 300, data.getData());
		    }
		}
	    }

	}

	if (requestCode == REQUEST_CODE_CROP) {
	    if (resultCode == Activity.RESULT_OK) {
		saveCropImage();
	    }
	}

	super.onActivityResult(requestCode, resultCode, data);
    }

    public String getRealPathFromURI(Uri contentUri) {
	String res = null;
	String[] proj = { MediaStore.Images.Media.DATA };
	Cursor cursor = getKaibesActivity().getContentResolver().query(
		contentUri, proj, null, null, null);
	if (cursor.moveToFirst()) {
	    ;
	    int column_index = cursor
		    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    res = cursor.getString(column_index);
	}
	cursor.close();
	return res;
    }

    // ============================================================================
    private void chooseImage() {
	Intent contentIntent = new Intent(Intent.ACTION_GET_CONTENT);
	contentIntent.addCategory(Intent.CATEGORY_OPENABLE);
	contentIntent.setType("image/*");
	startActivityForResult(Intent.createChooser(contentIntent, "请选择"),
		REQUEST_CODE_GET_CONTENT);
    }

    private void cropImage(int outputX, int outputY, Uri uri) {
	File file = new File(tempPhotoPath);
	if (file.exists()) {
	    file.delete();
	}
	try {
	    file.createNewFile();
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

	Intent cropIntent = new Intent();
	cropIntent.setAction("com.android.camera.action.CROP");
	cropIntent.putExtra("crop", "true");
	cropIntent.putExtra("aspectX", 1);
	cropIntent.putExtra("aspectY", 1);
	cropIntent.putExtra("scale", true);
	cropIntent.putExtra("return-data", false);
	cropIntent.putExtra("outputFormat",
		Bitmap.CompressFormat.JPEG.toString());
	cropIntent.putExtra("noFaceDetection", true);
	cropIntent.putExtra("outputX", outputX);
	cropIntent.putExtra("outputY", outputY);
	cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
	cropIntent.setDataAndType(uri, "image/*");
	startActivityForResult(cropIntent, REQUEST_CODE_CROP);

    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public String getPath(Context context, Uri uri) {
	String docId = DocumentsContract.getDocumentId(uri);

	// DocumentProvider
	if (DocumentsContract.isDocumentUri(context, uri)) {
	    // ExternalStorageProvider
	    if (isExternalStorageDocument(uri)) {
		String[] split = docId.split(":");
		if ("primary".equalsIgnoreCase(split[0])) {
		    return Environment.getExternalStorageDirectory() + "/"
			    + split[1];
		}
	    }
	    // DownloadsProvider
	    else if (isDownloadsDocument(uri)) {
		final Uri contentUri = ContentUris.withAppendedId(
			Uri.parse("content://downloads/public_downloads"),
			Long.valueOf(docId));
		return getDataColumn(contentUri, null, null);
	    }
	    // MediaProvider
	    else if (isMediaDocument(uri)) {
		String[] split = docId.split(":");
		return getDataColumn(
			MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "_id=?",
			new String[] { split[1] });
	    }
	}

	return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     * 
     * @param context
     *            The context.
     * @param uri
     *            The Uri to query.
     * @param selection
     *            (Optional) Filter used in the query.
     * @param selectionArgs
     *            (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Uri uri, String selection,
	    String[] selectionArgs) {

	Cursor cursor = null;
	final String column = "_data";
	final String[] projection = { column };

	try {
	    cursor = getActivity().getContentResolver().query(uri, projection,
		    selection, selectionArgs, null);
	    if (cursor != null && cursor.moveToFirst()) {
		final int index = cursor.getColumnIndexOrThrow(column);
		return cursor.getString(index);
	    }
	} finally {
	    if (cursor != null)
		cursor.close();
	}
	return null;
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
	return "com.android.externalstorage.documents".equals(uri
		.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
	return "com.android.providers.downloads.documents".equals(uri
		.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
	return "com.android.providers.media.documents".equals(uri
		.getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
	return "com.google.android.apps.photos.content".equals(uri
		.getAuthority());
    }

    private void saveCropImage() {
	Bitmap bitmap = BitmapFactory.decodeFile(tempPhotoPath);

	if (bitmap != null) {
	    FileOutputStream fos = null;
	    String photoname = getKaibesApplication().getUsername() + "_"
		    + System.currentTimeMillis() + ".jpg";
	    try {
		getKaibesApplication().setUserPhotoPathAndNotCreate(photoname);
		fos = new FileOutputStream(getKaibesApplication()
			.getUserPhotoPath().getPath());

		// 0-100，这里表示不压缩图片，有必要再压缩吧，先这样看看
		bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
	    } catch (IOException e) {
		e.printStackTrace();
	    } finally {
		try {
		    fos.flush();
		    fos.close();
		} catch (IOException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
	    }
	    getKaibesApplication().getUserInformationData().setPhoto(photoname);
	    getKaibesApplication().setUserPhotoBitmap(bitmap);
	    getKaibesActivity().refresh(
		    KaibesFragment.USER_INFORMATION_FRAGMENT,
		    UserInformationFragment.REFRESH_PHOTO);
	    getKaibesActivity().refresh(KaibesFragment.MAIN_FRAGMENT,
		    MainFragment.REFRESH_USER_IMAGE_VIEW);

	    // 我要发照片了，这个还是按照文件来处理，所以要使用action 15, 文件名photo, 文件夹"photo", 文件长度
	    getKaibesApplication().getUploadfiles().put(
		    photoname,
		    new File(getKaibesApplication().getUserPhotoPath()
			    .getPath()));
	    getKaibesApplication().sendData(1, SocketWorker.ACTION_PUT_PHOTO,
		    photoname, StaticValuesUtil.PHOTO,
		    getKaibesApplication().getUserPhotoPath().length());
	}
    }

}
